#include "RinexParser.h"
#include "SP3Interpolator.h"
#include "GPSSatelliteOrbit.h"
#include "Utils.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <ctime>

// 频率常量定义(Hz)
const std::unordered_map<std::string, std::pair<double, double>> FREQUENCY_MAP = {
    {"G", {1575.42e6, 1227.60e6}},  // GPS: L1, L2
    {"R", {1602.00e6, 1246.00e6}},  // GLONASS: G1, G2
    {"E", {1575.42e6, 1191.795e6}}, // Galileo: E1, E5a
    {"C", {1561.098e6, 1207.14e6}}, // BeiDou: B1, B2
    {"J", {1575.42e6, 1227.60e6}}   // QZSS: L1, L2
};

// 星历数据结构
struct EphemerisData {
    std::string prn;      // 卫星PRN号
    int year;             // 年
    int month;            // 月
    int day;              // 日
    int hour;             // 时
    int minute;           // 分
    double second;        // 秒
    
    double af0;           // 钟差(s)
    double af1;           // 钟漂(s/s)
    double af2;           // 钟漂变化率(s/s^2)
    
    double iode;          // 数据龄期
    double crs;           // 轨道半径正弦调和项(m)
    double deltaN;        // 平均角速度改正值(rad/s)
    double m0;            // 平近点角(rad)
    
    double cuc;           // 纬度幅角余弦调和项(rad)
    double e;             // 偏心率
    double cus;           // 纬度幅角正弦调和项(rad)
    double sqrtA;         // 轨道长半轴平方根(m^0.5)
    
    double toe;           // 星历参考时间(s)
    double cic;           // 轨道倾角余弦调和项(rad)
    double omega0;        // 升交点赤经(rad)
    double cis;           // 轨道倾角正弦调和项(rad)
    
    double i0;            // 轨道倾角(rad)
    double crc;           // 轨道半径余弦调和项(m)
    double omega;         // 近地点角距(rad)
    double omegaDot;      // 升交点赤经变化率(rad/s)
    
    double idot;          // 轨道倾角变化率(rad/s)
    double codesOnL2;     // L2上的码
    double gpsWeek;       // GPS周
    double l2pFlag;       // L2 P数据标志
    
    double svAccuracy;    // 卫星精度
    double svHealth;      // 卫星健康状态
    double tgd;           // 群延迟(s)
    double iodc;          // 钟数据龄期
    
    double transmissionTime; // 电文发送时间(s)
    double fitInterval;   // 拟合区间
};

RinexParser::RinexParser() : 
    sp3Interpolator_(std::make_unique<SP3Interpolator>()) {
    // Initialize any necessary components
}

RinexParser::~RinexParser() {
    // Clean up any resources
}

bool RinexParser::parseObservationFile(const std::string& filename) {
    RinexVersion version = detectRinexVersion(filename);
    obsVersion_ = version;
    
    switch (version) {
        case RinexVersion::V2x:
            return parseRinex2ObsFile(filename);
        case RinexVersion::V3x:
            return parseRinex3ObsFile(filename);
        default:
            std::cerr << "Unknown RINEX version for file: " << filename << std::endl;
            return false;
    }
}

bool RinexParser::parseObservationFile(const std::string& filename, const std::vector<std::string>& enabledSystems) {
    enabledGnssSystems_ = enabledSystems;
    return parseObservationFile(filename);
}

bool RinexParser::parseNavigationFile(const std::string& filename) {
    std::cout << "Parsing navigation file: " << filename << std::endl;
    
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open navigation file: " << filename << std::endl;
        return false;
    }
    
    // Detect file type
    RinexVersion version = detectRinexVersion(filename);
    std::string line;
    bool headerEnd = false;
    std::string currentSat;
    std::vector<double> ephemerisData;
    
    // Skip header
    while (std::getline(file, line) && !headerEnd) {
        if (line.find("END OF HEADER") != std::string::npos) {
            headerEnd = true;
        }
    }
    
    // Read ephemeris data
    while (std::getline(file, line)) {
        if (line.length() < 3) continue; // Skip empty lines
        
        // For RINEX 3.x, satellite ID is in columns 0-2
        // For RINEX 2.x, it's in columns 0-1
        if (version == RinexVersion::V3x) {
            currentSat = line.substr(0, 3);
        } else {
            std::string id = line.substr(0, 2);
            currentSat = std::string("G") + (id[0] == ' ' ? id.substr(1) : id);
        }
        
        // Start a new ephemeris record
        ephemerisData.clear();
        
        // Parse the first line
        for (int i = 3; i < line.length(); i += 19) {
            if (i + 19 <= line.length()) {
                try {
                    double value = std::stod(line.substr(i, 19));
                    ephemerisData.push_back(value);
                } catch (const std::exception& e) {
                    ephemerisData.push_back(0.0); // Default value if parsing fails
                }
            }
        }
        
        // Read additional lines for this ephemeris record
        int linesRead = 1;
        const int expectedLines = 7; // Navigation message typically has 8 lines total
        
        while (linesRead < expectedLines && std::getline(file, line)) {
            // Parse additional lines
            for (int i = 3; i < line.length(); i += 19) {
                if (i + 19 <= line.length()) {
                    try {
                        double value = std::stod(line.substr(i, 19));
                        ephemerisData.push_back(value);
                    } catch (const std::exception& e) {
                        ephemerisData.push_back(0.0); // Default value if parsing fails
                    }
                }
            }
            linesRead++;
        }
        
        // Store complete ephemeris data
        if (linesRead == expectedLines) {
            navData_[currentSat] = ephemerisData;
            
            // Initialize satellite orbit objects
            if (satelliteOrbits_.find(currentSat) == satelliteOrbits_.end()) {
                satelliteOrbits_[currentSat] = GPSSatelliteOrbit();
            }
            
            // Set ephemeris data for the satellite
            satelliteOrbits_[currentSat].setOrbitParams(ephemerisData);
        }
    }
    
    std::cout << "Parsed " << navData_.size() << " satellite ephemeris records from " << filename << std::endl;
    return !navData_.empty();
}

bool RinexParser::parseSP3File(const std::string& filename) {
    bool result = sp3Interpolator_->readSP3File(filename);
    
    if (result) {
        usePreciseOrbit_ = true;
        std::cout << "SP3文件解析成功：" << filename << std::endl;
    }
    
    return result;
}

// Add methods to support multiple files
bool RinexParser::parseMultipleObservationFiles(const std::vector<std::string>& filenames) {
    bool success = true;
    for (const std::string& filename : filenames) {
        if (!parseObservationFile(filename)) {
            success = false;
            std::cerr << "Failed to parse observation file: " << filename << std::endl;
        }
    }
    return success;
}

bool RinexParser::parseMultipleObservationFiles(const std::vector<std::pair<std::string, std::vector<std::string>>>& fileConfigs) {
    bool success = true;
    for (const auto& config : fileConfigs) {
        if (!parseObservationFile(config.first, config.second)) {
            success = false;
            std::cerr << "Failed to parse observation file: " << config.first << std::endl;
        }
    }
    return success;
}

bool RinexParser::parseMultipleNavigationFiles(const std::vector<std::string>& filenames) {
    bool success = true;
    for (const std::string& filename : filenames) {
        if (!parseNavigationFile(filename)) {
            success = false;
            std::cerr << "Failed to parse navigation file: " << filename << std::endl;
        }
    }
    return success;
}

bool RinexParser::parseMultipleSP3Files(const std::vector<std::string>& filenames) {
    bool success = true;
    for (const std::string& filename : filenames) {
        if (!parseSP3File(filename)) {
            success = false;
            std::cerr << "Failed to parse SP3 file: " << filename << std::endl;
        }
    }
    return success;
}

std::vector<GNSSObservation> RinexParser::getObservations() const {
    return observations_;
}

std::vector<GNSSObservation> RinexParser::getObservationsBySystem(const std::string& system) const {
    std::vector<GNSSObservation> filtered;
    int systemIndex = GNSSObservation::addSystem(system);
    
    for (const auto& obs : observations_) {
        if (obs.system == systemIndex) {
            filtered.push_back(obs);
        }
    }
    return filtered;
}

std::vector<GNSSObservation> RinexParser::getObservationsBySystems(const std::vector<std::string>& systems) const {
    if (systems.empty()) {
        return observations_; // 如果系统列表为空，返回所有观测数据
    }
    
    std::vector<GNSSObservation> filtered;
    std::vector<int> systemIndices;
    
    // 预先转换系统字符串为索引，避免重复转换
    for (const auto& system : systems) {
        systemIndices.push_back(GNSSObservation::addSystem(system));
    }
    
    // 过滤满足任一系统的观测数据
    for (const auto& obs : observations_) {
        if (std::find(systemIndices.begin(), systemIndices.end(), obs.system) != systemIndices.end()) {
            filtered.push_back(obs);
        }
    }
    
    return filtered;
}

StationInfo RinexParser::getStationInfo() const {
    return stationInfo_;
}

void RinexParser::useHighPrecisionOrbit(bool use) {
    usePreciseOrbit_ = use;
}

bool RinexParser::isUsingHighPrecisionOrbit() const {
    return usePreciseOrbit_;
}

// Continue implementing remaining methods...

// End with stubs for each method that needs to be completed later
RinexVersion RinexParser::detectRinexVersion(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return RinexVersion::Unknown;
    }
    
    std::string line;
    // 读取第一行，检查版本信息
    if (std::getline(file, line)) {
        // RINEX 3.x 格式的版本标记在第1-9列
        if (line.length() >= 9) {
            std::string versionStr = line.substr(0, 9);
            // 查找版本号
            size_t pos = versionStr.find(".");
            if (pos != std::string::npos && pos > 0 && pos < versionStr.length() - 1) {
                char majorVersion = versionStr[pos - 1];
                
                if (majorVersion == '3') {
                    return RinexVersion::V3x;
                } else if (majorVersion == '2') {
                    return RinexVersion::V2x;
                }
            }
        }
        
        // 检查RINEX 2.x的特定标记
        // 在RINEX 2.x中，版本信息通常在第60-80列
        if (line.length() >= 80) {
            std::string versionInfo = line.substr(60);
            if (versionInfo.find("RINEX VERSION / TYPE") != std::string::npos) {
                // 检查版本号
                if (line.length() >= 20) {
                    std::string versionStr = line.substr(0, 20);
                    if (versionStr.find("2.") != std::string::npos) {
                        return RinexVersion::V2x;
                    } else if (versionStr.find("3.") != std::string::npos) {
                        return RinexVersion::V3x;
                    }
                }
            }
        }
    }
    
    // 如果无法确定版本，尝试基于文件扩展名判断
    if (filename.length() > 4) {
        std::string ext = filename.substr(filename.length() - 3);
        if (ext == "rnx" || ext == "RNX") {
            // .rnx 通常是RINEX 3.x格式
            return RinexVersion::V3x;
        } else if (ext == ".o" || ext == ".O" || ext == "obs" || ext == "OBS") {
            // .xxo 通常是RINEX 2.x格式
            return RinexVersion::V2x;
        }
    }
    
    // 默认返回RINEX 2.x
    return RinexVersion::V2x;
}

void RinexParser::computeSatelliteGeometry() {
    // 为所有观测值计算卫星几何信息
    for (auto& obs : observations_) {
        // 获取卫星位置
        std::vector<double> satPos;
        
        // 根据配置选择使用广播星历或精密星历
        if (usePreciseOrbit_ && sp3Interpolator_) {
            satPos = calculatePrecisePosition(obs.getSatellite(), obs.time);
        } else {
            satPos = calculateBroadcastPosition(obs.getSatellite(), obs.time);
        }
        
        // 如果成功获取卫星位置，计算高度角和方位角
        if (satPos.size() == 3 && satPos[0] != 0.0 && satPos[1] != 0.0 && satPos[2] != 0.0) {
            calculateElevationAndAzimuth(obs, satPos);
            
            // 存储卫星位置
            obs.satellitePosition = satPos;
        }
    }
    
    // 应用高度角筛选
    if (minElevation_ > 0.0) {
        auto it = observations_.begin();
        while (it != observations_.end()) {
            if (it->elevation < minElevation_) {
                it = observations_.erase(it);
            } else {
                ++it;
            }
        }
    }
}

void RinexParser::parseHeader(std::ifstream& file) {
    if (!file.is_open() || !file.good()) {
        return;
    }
    
    std::string line;
    bool headerEnd = false;
    
    // 重置文件指针到开始位置
    file.seekg(0, std::ios::beg);
    
    // 解析头部直到END OF HEADER标记
    while (std::getline(file, line) && !headerEnd) {
        // 检查行长度
        if (line.length() < 60) {
            continue;
        }
        
        // 获取行标记（通常在第60-80列）
        std::string label = line.length() >= 80 ? line.substr(60) : line.substr(line.length() - 20);
        
        // 处理不同类型的头部记录
        if (label.find("RINEX VERSION / TYPE") != std::string::npos) {
            // 解析RINEX版本和文件类型
            if (line.length() >= 20) {
                std::string versionStr = line.substr(0, 20);
                size_t pos = versionStr.find(".");
                if (pos != std::string::npos && pos > 0) {
                    int majorVersion = versionStr[pos - 1] - '0';
                    int minorVersion = versionStr[pos + 1] - '0';
                    
                    if (majorVersion == 2) {
                        version_ = RinexVersion::V2x;
                    } else if (majorVersion == 3) {
                        version_ = RinexVersion::V3x;
                    }
                    
                    // 存储具体版本号
                    versionMajor_ = majorVersion;
                    versionMinor_ = minorVersion;
                }
                
                // 解析文件类型
                if (line.length() >= 40) {
                    char fileType = line[20];
                    if (fileType == 'O' || fileType == 'o') {
                        fileType_ = RinexFileType::Observation;
                    } else if (fileType == 'N' || fileType == 'n') {
                        fileType_ = RinexFileType::Navigation;
                    }
                }
            }
        } 
        else if (label.find("MARKER NAME") != std::string::npos) {
            // 解析测站名
            stationInfo_.name = line.substr(0, 60);
            // 去除尾部空格
            stationInfo_.name.erase(stationInfo_.name.find_last_not_of(" \t\n\r\f\v") + 1);
        }
        else if (label.find("APPROX POSITION XYZ") != std::string::npos) {
            // 解析测站近似坐标
            if (line.length() >= 42) {
                try {
                    stationInfo_.x = std::stod(line.substr(0, 14));
                    stationInfo_.y = std::stod(line.substr(14, 14));
                    stationInfo_.z = std::stod(line.substr(28, 14));
                    
                    // 计算大地坐标（纬度、经度、高度）
                    // 这里可以调用Utils中的坐标转换函数
                    // Utils::ecef2llh(stationInfo_.x, stationInfo_.y, stationInfo_.z, 
                    //                stationInfo_.lat, stationInfo_.lon, stationInfo_.height);
                } catch (const std::exception& e) {
                    std::cerr << "解析测站坐标时出错: " << e.what() << std::endl;
                }
            }
        }
        else if (label.find("# / TYPES OF OBSERV") != std::string::npos || 
                 label.find("SYS / # / OBS TYPES") != std::string::npos) {
            // RINEX 2.x和3.x的观测类型格式不同
            if (version_ == RinexVersion::V2x) {
                // RINEX 2.x格式
                try {
                    int numObsTypes = std::stoi(line.substr(0, 6));
                    for (int i = 0; i < numObsTypes; ++i) {
                        int pos = 10 + i * 6;
                        if (pos + 2 <= static_cast<int>(line.length())) {
                            std::string obsType = line.substr(pos, 2);
                            // 创建ObservationType结构体并添加到vector
                            ObservationType type;
                            type.system = "G"; // 默认为GPS
                            type.code = obsType;
                            type.frequency = 0.0; // 默认频率，后续可更新
                            obsTypes_.push_back(type);
                        }
                    }
                } catch (const std::exception& e) {
                    std::cerr << "解析观测类型时出错: " << e.what() << std::endl;
                }
            } else if (version_ == RinexVersion::V3x) {
                // RINEX 3.x格式 - 需要处理系统特定的观测类型
                char sysId = line[0];
                try {
                    int numObsTypes = std::stoi(line.substr(1, 5));
                    for (int i = 0; i < numObsTypes; ++i) {
                        int pos = 7 + i * 4;
                        if (pos + 3 <= static_cast<int>(line.length())) {
                            std::string obsType = line.substr(pos, 3);
                            // 存储系统特定的观测类型
                            obsTypesBySys_[std::string(1, sysId)].push_back(obsType);
                            
                            // 同时创建ObservationType结构体并添加到vector
                            ObservationType type;
                            type.system = std::string(1, sysId);
                            type.code = obsType;
                            type.frequency = 0.0; // 默认频率，后续可更新
                            obsTypes_.push_back(type);
                        }
                    }
                } catch (const std::exception& e) {
                    std::cerr << "解析观测类型时出错: " << e.what() << std::endl;
                }
            }
        }
        else if (label.find("TIME OF FIRST OBS") != std::string::npos) {
            // 解析第一个观测时间
            try {
                int year = std::stoi(line.substr(0, 6));
                int month = std::stoi(line.substr(6, 6));
                int day = std::stoi(line.substr(12, 6));
                int hour = std::stoi(line.substr(18, 6));
                int minute = std::stoi(line.substr(24, 6));
                double second = std::stod(line.substr(30, 13));
                
                // 存储第一个观测时间
                firstObsTime_.year = year;
                firstObsTime_.month = month;
                firstObsTime_.day = day;
                firstObsTime_.hour = hour;
                firstObsTime_.minute = minute;
                firstObsTime_.second = second;
            } catch (const std::exception& e) {
                std::cerr << "解析观测时间时出错: " << e.what() << std::endl;
            }
        }
        else if (label.find("END OF HEADER") != std::string::npos) {
            // 头部结束标记
            headerEnd = true;
        }
    }
    
    // 保存当前文件位置，用于后续数据解析
    headerEndPos_ = file.tellg();
}

void RinexParser::parseObservationRecord(std::ifstream& file) {
    if (!file.is_open() || !file.good() || headerEndPos_ == -1) {
        return;
    }
    
    // 将文件指针设置到头部结束位置
    file.seekg(headerEndPos_);
    
    std::string line;
    int epochIndex = 0;
    
    // 根据RINEX版本选择不同的解析方法
    if (version_ == RinexVersion::V2x) {
        // RINEX 2.x格式解析
        while (std::getline(file, line)) {
            // 检查是否是历元行（RINEX 2.x中以年份开始）
            if (line.length() >= 3 && (line[0] == ' ' || std::isdigit(line[0]))) {
                // 解析历元时间
                try {
                    int year = std::stoi(line.substr(1, 2));
                    // 处理两位数年份
                    year = (year >= 80) ? 1900 + year : 2000 + year;
                    
                    int month = std::stoi(line.substr(4, 2));
                    int day = std::stoi(line.substr(7, 2));
                    int hour = std::stoi(line.substr(10, 2));
                    int minute = std::stoi(line.substr(13, 2));
                    double second = std::stod(line.substr(16, 11));
                    
                    // 计算GPS时间
                    Utils::GPSTime gpsTimeStruct = Utils::ymdhmsToGpst(year, month, day, hour, minute, second);
                    double gpsTime = gpsTimeStruct.week * 604800.0 + gpsTimeStruct.secondsOfWeek; // 转换为连续秒
                    
                    // 获取历元标志
                    int epochFlag = std::stoi(line.substr(28, 1));
                    
                    // 只处理正常观测值（标志为0或1）
                    if (epochFlag <= 1) {
                        // 获取卫星数量
                        int numSats = std::stoi(line.substr(29, 3));
                        
                        // 读取卫星列表
                        std::vector<std::string> satList;
                        int satsInFirstLine = std::min(12, numSats); // 第一行最多12颗卫星
                        
                        for (int i = 0; i < satsInFirstLine; ++i) {
                            int pos = 32 + i * 3;
                            if (pos + 3 <= static_cast<int>(line.length())) {
                                std::string satId = line.substr(pos, 3);
                                satList.push_back(satId);
                            }
                        }
                        
                        // 如果卫星数量超过12，需要读取额外的行
                        int remainingSats = numSats - satsInFirstLine;
                        while (remainingSats > 0) {
                            if (!std::getline(file, line)) {
                                break;
                            }
                            
                            int satsInThisLine = std::min(12, remainingSats);
                            for (int i = 0; i < satsInThisLine; ++i) {
                                int pos = 32 + i * 3;
                                if (pos + 3 <= static_cast<int>(line.length())) {
                                    std::string satId = line.substr(pos, 3);
                                    satList.push_back(satId);
                                }
                            }
                            
                            remainingSats -= satsInThisLine;
                        }
                        
                        // 读取每颗卫星的观测值
                        for (const auto& satId : satList) {
                            GNSSObservation obs;
                            obs.time = gpsTime;
                            obs.satellite = GNSSObservation::addSatellite(satId);
                            obs.system = GNSSObservation::addSystem(satId.substr(0, 1)); // 第一个字符表示系统
                            obs.station = GNSSObservation::addStation(stationInfo_.name);
                            obs.epochIndex = epochIndex;
                            
                            // 读取观测值行
                            if (!std::getline(file, line)) {
                                break;
                            }
                            
                            // 解析观测值
                            int numObsTypes = static_cast<int>(obsTypes_.size());
                            int numLines = (numObsTypes + 4) / 5; // 每行最多5个观测值
                            
                            std::vector<double> obsValues;
                            for (int i = 0; i < numLines; ++i) {
                                if (i > 0 && !std::getline(file, line)) {
                                    break;
                                }
                                
                                int obsInThisLine = std::min(5, numObsTypes - i * 5);
                                for (int j = 0; j < obsInThisLine; ++j) {
                                    int pos = j * 16;
                                    if (pos + 14 <= static_cast<int>(line.length())) {
                                        std::string valueStr = line.substr(pos, 14);
                                        // 检查是否有有效值
                                        if (!valueStr.empty() && valueStr.find_first_not_of(" ") != std::string::npos) {
                                            try {
                                                double value = std::stod(valueStr);
                                                obsValues.push_back(value);
                                            } catch (const std::exception&) {
                                                obsValues.push_back(0.0); // 无效值用0替代
                                            }
                                        } else {
                                            obsValues.push_back(0.0); // 空值用0替代
                                        }
                                    } else {
                                        obsValues.push_back(0.0); // 缺失值用0替代
                                    }
                                }
                            }
                            
                            // 将观测值存储到观测结构中
                            for (size_t i = 0; i < obsValues.size() && i < obsTypes_.size(); ++i) {
                                int typeIndex = GNSSObservation::getObsTypeIndex(obsTypes_[i].code);
                                obs.obsValues[typeIndex] = obsValues[i];
                            }
                            
                            // 提取双频观测值
                            extractDualFrequencyObs(obs);
                            
                            // 添加到观测列表
                            observations_.push_back(obs);
                        }
                        
                        // 增加历元索引
                        epochIndex++;
                    }
                } catch (const std::exception& e) {
                    std::cerr << "解析观测记录时出错: " << e.what() << std::endl;
                }
            }
        }
    } else if (version_ == RinexVersion::V3x) {
        // RINEX 3.x格式解析
        while (std::getline(file, line)) {
            // 检查是否是历元行（RINEX 3.x中以'>'开始）
            if (line.length() >= 1 && line[0] == '>') {
                // 解析历元时间
                try {
                    int year = std::stoi(line.substr(2, 4));
                    int month = std::stoi(line.substr(7, 2));
                    int day = std::stoi(line.substr(10, 2));
                    int hour = std::stoi(line.substr(13, 2));
                    int minute = std::stoi(line.substr(16, 2));
                    double second = std::stod(line.substr(19, 11));
                    
                    // 计算GPS时间
                    Utils::GPSTime gpsTimeStruct = Utils::ymdhmsToGpst(year, month, day, hour, minute, second);
                    double gpsTime = gpsTimeStruct.week * 604800.0 + gpsTimeStruct.secondsOfWeek; // 转换为连续秒
                    
                    // 获取历元标志
                    int epochFlag = std::stoi(line.substr(31, 1));
                    
                    // 只处理正常观测值（标志为0或1）
                    if (epochFlag <= 1) {
                        // 获取卫星数量
                        int numSats = std::stoi(line.substr(32, 3));
                        
                        // 读取每颗卫星的观测值
                        for (int i = 0; i < numSats; ++i) {
                            if (!std::getline(file, line)) {
                                break;
                            }
                            
                            // RINEX 3.x中，卫星ID在行首
                            if (line.length() >= 3) {
                                std::string satId = line.substr(0, 3);
                                std::string sysId = satId.substr(0, 1);
                                
                                // 检查是否是我们要处理的系统
                                if (enabledSystems_.empty() || 
                                    std::find(enabledSystems_.begin(), enabledSystems_.end(), sysId) != enabledSystems_.end()) {
                                    
                                    GNSSObservation obs;
                                    obs.time = gpsTime;
                                    obs.satellite = GNSSObservation::addSatellite(satId);
                                    obs.system = GNSSObservation::addSystem(sysId);
                                    obs.station = GNSSObservation::addStation(stationInfo_.name);
                                    obs.epochIndex = epochIndex;
                                    
                                    // 获取该系统的观测类型
                                    const auto& sysObsTypes = obsTypesBySys_[sysId];
                                    
                                    // 解析观测值
                                    for (size_t j = 0; j < sysObsTypes.size(); ++j) {
                                        int pos = 3 + j * 16;
                                        if (pos + 14 <= static_cast<int>(line.length())) {
                                            std::string valueStr = line.substr(pos, 14);
                                            // 检查是否有有效值
                                            if (!valueStr.empty() && valueStr.find_first_not_of(" ") != std::string::npos) {
                                                try {
                                                    double value = std::stod(valueStr);
                                                    int typeIndex = GNSSObservation::getObsTypeIndex(sysObsTypes[j]);
                                                    obs.obsValues[typeIndex] = value;
                                                } catch (const std::exception&) {
                                                    // 无效值忽略
                                                }
                                            }
                                        }
                                    }
                                    
                                    // 提取双频观测值
                                    extractDualFrequencyObs(obs);
                                    
                                    // 添加到观测列表
                                    observations_.push_back(obs);
                                }
                            }
                        }
                        
                        // 增加历元索引
                        epochIndex++;
                    }
                } catch (const std::exception& e) {
                    std::cerr << "解析观测记录时出错: " << e.what() << std::endl;
                }
            }
        }
    }
    
    // 完成解析后，计算卫星几何信息
    computeSatelliteGeometry();
}

void RinexParser::calculateElevationAndAzimuth(GNSSObservation& obs, const std::vector<double>& satPos) {
    if (satPos.size() < 3) {
        return;
    }
    
    // 获取测站ECEF坐标
    double stationX = stationInfo_.x;
    double stationY = stationInfo_.y;
    double stationZ = stationInfo_.z;
    
    // 计算从测站到卫星的向量
    double dx = satPos[0] - stationX;
    double dy = satPos[1] - stationY;
    double dz = satPos[2] - stationZ;
    
    // 计算距离
    double distance = std::sqrt(dx*dx + dy*dy + dz*dz);
    
    // 归一化向量
    dx /= distance;
    dy /= distance;
    dz /= distance;
    
    // 存储视线向量
    obs.lineOfSight = {dx, dy, dz};
    
    // 将ECEF坐标转换为大地坐标（弧度）
    double a = 6378137.0; // WGS84椭球长半轴
    double f = 1.0 / 298.257223563; // WGS84扁率
    double e2 = 2*f - f*f; // 第一偏心率平方
    
    double p = std::sqrt(stationX*stationX + stationY*stationY);
    double theta = std::atan2(stationZ * a, p * (1-e2));
    double lat = std::atan2(stationZ + e2/(1-e2) * a * std::pow(std::sin(theta), 3), 
                           p - e2 * a * std::pow(std::cos(theta), 3));
    double lon = std::atan2(stationY, stationX);
    
    // 构建从ECEF到ENU的旋转矩阵
    double sinLat = std::sin(lat);
    double cosLat = std::cos(lat);
    double sinLon = std::sin(lon);
    double cosLon = std::cos(lon);
    
    // 计算ENU坐标
    double e = -dx * sinLon + dy * cosLon;
    double n = -dx * sinLat * cosLon - dy * sinLat * sinLon + dz * cosLat;
    double u = dx * cosLat * cosLon + dy * cosLat * sinLon + dz * sinLat;
    
    // 计算高度角和方位角
    obs.elevation = std::asin(u) * 180.0 / M_PI; // 转为度
    obs.azimuth = std::atan2(e, n) * 180.0 / M_PI; // 转为度
    
    // 确保方位角在0-360度范围内
    if (obs.azimuth < 0) {
        obs.azimuth += 360.0;
    }
}

std::vector<double> RinexParser::calculateSatellitePosition(const std::string& satId, double time) {
    (void) satId; // Mark as intentionally unused
    (void) time;  // Mark as intentionally unused
    // Minimal implementation
    return std::vector<double>(3, 0.0);
}

std::vector<double> RinexParser::calculateBroadcastPosition(const std::string& satId, double time) {
    std::vector<double> position(3, 0.0);
    
    // 检查是否有该卫星的星历数据
    auto it = satelliteOrbits_.find(satId);
    if (it == satelliteOrbits_.end()) {
        return position;
    }
    
    // 使用卫星轨道对象计算位置
    GPSSatelliteOrbit& orbit = it->second;
    
    // 计算卫星位置
    std::vector<double> pos, vel;
    if (orbit.computePosVel(time, pos, vel)) {
        if (pos.size() >= 3) {
            position = pos;
        }
    }
    
    return position;
}

std::vector<double> RinexParser::calculatePrecisePosition(const std::string& satId, double time) {
    std::vector<double> pos(3, 0.0);
    
    if (sp3Interpolator_->getSatellitePosVel(satId, time, pos, nullptr)) {
        return pos;
    }
    
    return calculateBroadcastPosition(satId, time);
}

void RinexParser::initializeSatelliteOrbits() {
    // 遍历所有卫星轨道对象，进行必要的初始化
    for (auto& pair : satelliteOrbits_) {
        GPSSatelliteOrbit& orbit = pair.second;
        
        // 设置卫星PRN号
        std::string satId = pair.first;
        orbit.setPRN(satId);
        
        // 如果使用精密星历，设置SP3插值器
        if (usePreciseOrbit_ && sp3Interpolator_ != nullptr) {
            orbit.setSP3Interpolator(sp3Interpolator_.get());
            orbit.setUsePreciseOrbit(true);
        }
    }
    
    // 如果使用精密星历，初始化SP3插值器
    if (usePreciseOrbit_ && sp3Interpolator_) {
        // SP3Interpolator已经在readSP3File方法中初始化
    }
}

bool RinexParser::parseRinex2ObsFile(const std::string& filename) {
    std::cout << "解析RINEX 2.x文件: " << filename << std::endl;
    
    // 打开文件
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return false;
    }
    
    // 设置文件版本
    version_ = RinexVersion::V2x;
    
    // 解析头部
    parseHeader(file);
    
    // 检查文件类型
    if (fileType_ != RinexFileType::Observation) {
        std::cerr << "文件不是观测文件: " << filename << std::endl;
        return false;
    }
    
    // 解析观测记录
    parseObservationRecord(file);
    
    // 关闭文件
    file.close();
    
    // 检查是否成功解析到观测数据
    if (observations_.empty()) {
        std::cerr << "未解析到观测数据: " << filename << std::endl;
        return false;
    }
    
    std::cout << "成功解析RINEX 2.x文件: " << filename << std::endl;
    std::cout << "观测数据数量: " << observations_.size() << std::endl;
    
    return true;
}

bool RinexParser::parseRinex3ObsFile(const std::string& filename) {
    std::cout << "解析RINEX 3.x文件: " << filename << std::endl;
    
    // 打开文件
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filename << std::endl;
        return false;
    }
    
    // 设置文件版本
    version_ = RinexVersion::V3x;
    
    // 解析头部
    parseHeader(file);
    
    // 检查文件类型
    if (fileType_ != RinexFileType::Observation) {
        std::cerr << "文件不是观测文件: " << filename << std::endl;
        return false;
    }
    
    // 解析观测记录
    parseObservationRecord(file);
    
    // 关闭文件
    file.close();
    
    // 检查是否成功解析到观测数据
    if (observations_.empty()) {
        std::cerr << "未解析到观测数据: " << filename << std::endl;
        return false;
    }
    
    std::cout << "成功解析RINEX 3.x文件: " << filename << std::endl;
    std::cout << "观测数据数量: " << observations_.size() << std::endl;
    
    return true;
}

void RinexParser::parseRinex3ObsTypes(const std::string& line) {
    // 检查行长度
    if (line.length() < 7) {
        return;
    }
    
    // 获取卫星系统
    char sysId = line[0];
    std::string system(1, sysId);
    
    // 获取观测类型数量
    int numObsTypes = 0;
    try {
        numObsTypes = std::stoi(line.substr(1, 5));
    } catch (const std::exception& e) {
        std::cerr << "解析观测类型数量时出错: " << e.what() << std::endl;
        return;
    }
    
    // 解析观测类型
    std::vector<std::string> obsTypes;
    
    // 第一行最多可以包含13个观测类型
    int obsInFirstLine = std::min(13, numObsTypes);
    
    for (int i = 0; i < obsInFirstLine; ++i) {
        int pos = 7 + i * 4;
        if (pos + 3 <= static_cast<int>(line.length())) {
            std::string obsType = line.substr(pos, 3);
            obsTypes.push_back(obsType);
        }
    }
    
    // 如果观测类型数量超过13，需要读取额外的行
    // 这部分需要在调用此函数的地方处理
    
    // 存储系统特定的观测类型
    obsTypesBySys_[system] = obsTypes;
    
    // 如果是我们要处理的系统，添加到全局观测类型列表
    if (enabledSystems_.empty() || 
        std::find(enabledSystems_.begin(), enabledSystems_.end(), system) != enabledSystems_.end()) {
        for (const auto& obsType : obsTypes) {
            // 检查是否已经存在相同的观测类型
            bool exists = false;
            for (const auto& existingType : obsTypes_) {
                if (existingType.code == obsType) {
                    exists = true;
                    break;
                }
            }
            // 如果不存在，则添加
            if (!exists) {
                ObservationType type;
                type.system = system;
                type.code = obsType;
                type.frequency = 0.0; // 默认频率
                obsTypes_.push_back(type);
            }
        }
    }
}

void RinexParser::extractDualFrequencyObs(GNSSObservation& obs) {
    // 根据卫星系统选择不同的观测码
    std::string system = obs.getSystem();
    
    // 默认频率
    double f1 = 0.0, f2 = 0.0;
    
    // 伪距和载波相位观测值
    double p1 = 0.0, p2 = 0.0, l1 = 0.0, l2 = 0.0;
    bool foundP1 = false, foundP2 = false, foundL1 = false, foundL2 = false;
    
    // 根据不同的卫星系统选择观测码
    if (system == "G") {
        // GPS
        // 尝试不同的观测码组合
        // 伪距: C1C/C1P/C1W -> C2C/C2P/C2W
        // 载波相位: L1C/L1P/L1W -> L2C/L2P/L2W
        
        // 伪距1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")];
            foundP1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C1P")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1P")];
            foundP1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1W")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C1W")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1W")];
            foundP1 = true;
        }
        
        // 伪距2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C2C")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2C")];
            foundP2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C2P")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2P")];
            foundP2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2W")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C2W")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2W")];
            foundP2 = true;
        }
        
        // 载波相位1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")];
            foundL1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L1P")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1P")];
            foundL1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1W")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L1W")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1W")];
            foundL1 = true;
        }
        
        // 载波相位2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L2C")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2C")];
            foundL2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L2P")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2P")];
            foundL2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2W")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L2W")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2W")];
            foundL2 = true;
        }
        
        // GPS频率
        f1 = 1575.42e6; // L1
        f2 = 1227.60e6; // L2
    } 
    else if (system == "R") {
        // GLONASS
        // 伪距: C1C/C1P -> C2C/C2P
        // 载波相位: L1C/L1P -> L2C/L2P
        
        // 伪距1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")];
            foundP1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C1P")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1P")];
            foundP1 = true;
        }
        
        // 伪距2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C2C")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2C")];
            foundP2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C2P")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2P")];
            foundP2 = true;
        }
        
        // 载波相位1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")];
            foundL1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L1P")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1P")];
            foundL1 = true;
        }
        
        // 载波相位2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2C")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L2C")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2C")];
            foundL2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2P")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L2P")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2P")];
            foundL2 = true;
        }
        
        // GLONASS频率（这里使用名义频率，实际应根据频道号计算）
        f1 = 1602.00e6; // L1
        f2 = 1246.00e6; // L2
    } 
    else if (system == "E") {
        // Galileo
        // 伪距: C1X/C1C -> C5X/C5Q
        // 载波相位: L1X/L1C -> L5X/L5Q
        
        // 伪距1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1X")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C1X")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1X")];
            foundP1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C1C")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C1C")];
            foundP1 = true;
        }
        
        // 伪距2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C5X")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C5X")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C5X")];
            foundP2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C5Q")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C5Q")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C5Q")];
            foundP2 = true;
        }
        
        // 载波相位1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1X")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L1X")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1X")];
            foundL1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L1C")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L1C")];
            foundL1 = true;
        }
        
        // 载波相位2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L5X")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L5X")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L5X")];
            foundL2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L5Q")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L5Q")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L5Q")];
            foundL2 = true;
        }
        
        // Galileo频率
        f1 = 1575.42e6; // E1
        f2 = 1176.45e6; // E5a
    } 
    else if (system == "C") {
        // BeiDou
        // 伪距: C2I/C2X -> C7I/C7X
        // 载波相位: L2I/L2X -> L7I/L7X
        
        // 伪距1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2I")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C2I")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2I")];
            foundP1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C2X")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C2X")] != 0.0) {
            p1 = obs.obsValues[GNSSObservation::getObsTypeIndex("C2X")];
            foundP1 = true;
        }
        
        // 伪距2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C7I")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("C7I")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C7I")];
            foundP2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("C7X")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("C7X")] != 0.0) {
            p2 = obs.obsValues[GNSSObservation::getObsTypeIndex("C7X")];
            foundP2 = true;
        }
        
        // 载波相位1
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2I")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L2I")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2I")];
            foundL1 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L2X")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L2X")] != 0.0) {
            l1 = obs.obsValues[GNSSObservation::getObsTypeIndex("L2X")];
            foundL1 = true;
        }
        
        // 载波相位2
        if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L7I")) != obs.obsValues.end() && 
            obs.obsValues[GNSSObservation::getObsTypeIndex("L7I")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L7I")];
            foundL2 = true;
        } else if (obs.obsValues.find(GNSSObservation::getObsTypeIndex("L7X")) != obs.obsValues.end() && 
                   obs.obsValues[GNSSObservation::getObsTypeIndex("L7X")] != 0.0) {
            l2 = obs.obsValues[GNSSObservation::getObsTypeIndex("L7X")];
            foundL2 = true;
        }
        
        // BeiDou频率
        f1 = 1561.098e6; // B1
        f2 = 1207.140e6; // B2
    }
    
    // 存储提取的观测值
    if (foundP1 && foundP2 && foundL1 && foundL2) {
        obs.P1 = p1;
        obs.P2 = p2;
        obs.L1 = l1;
        obs.L2 = l2;
        obs.f1 = f1;
        obs.f2 = f2;
    } else {
        // 如果缺少任何一个观测值，将其标记为无效
        obs.P1 = 0.0;
        obs.P2 = 0.0;
        obs.L1 = 0.0;
        obs.L2 = 0.0;
        obs.f1 = 0.0;
        obs.f2 = 0.0;
    }
}

void RinexParser::parseNavigationRecord(std::ifstream& file) {
    if (!file.is_open() || !file.good() || headerEndPos_ == -1) {
        return;
    }
    
    // 将文件指针设置到头部结束位置
    file.seekg(headerEndPos_);
    
    std::string line;
    
    // 根据RINEX版本选择不同的解析方法
    if (version_ == RinexVersion::V2x) {
        // RINEX 2.x导航消息格式
        while (std::getline(file, line)) {
            // 检查是否是卫星PRN行
            if (line.length() >= 2 && line[0] == ' ' && std::isdigit(line[1])) {
                // 解析卫星PRN
                std::string satId = "G" + line.substr(1, 2); // 假设是GPS卫星
                
                // 解析历元时间
                try {
                    int year = std::stoi(line.substr(3, 2));
                    // 处理两位数年份
                    year = (year >= 80) ? 1900 + year : 2000 + year;
                    
                    int month = std::stoi(line.substr(6, 2));
                    int day = std::stoi(line.substr(9, 2));
                    int hour = std::stoi(line.substr(12, 2));
                    int minute = std::stoi(line.substr(15, 2));
                    double second = std::stod(line.substr(18, 4));
                    
                    // 创建星历数据结构
                    EphemerisData ephData;
                    ephData.prn = satId;
                    ephData.year = year;
                    ephData.month = month;
                    ephData.day = day;
                    ephData.hour = hour;
                    ephData.minute = minute;
                    ephData.second = second;
                    
                    // 解析卫星钟差参数
                    ephData.af0 = std::stod(line.substr(22, 19));
                    ephData.af1 = std::stod(line.substr(41, 19));
                    ephData.af2 = std::stod(line.substr(60, 19));
                    
                    // 读取第二行
                    if (!std::getline(file, line)) break;
                    ephData.iode = std::stod(line.substr(3, 19));
                    ephData.crs = std::stod(line.substr(22, 19));
                    ephData.deltaN = std::stod(line.substr(41, 19));
                    ephData.m0 = std::stod(line.substr(60, 19));
                    
                    // 读取第三行
                    if (!std::getline(file, line)) break;
                    ephData.cuc = std::stod(line.substr(3, 19));
                    ephData.e = std::stod(line.substr(22, 19));
                    ephData.cus = std::stod(line.substr(41, 19));
                    ephData.sqrtA = std::stod(line.substr(60, 19));
                    
                    // 读取第四行
                    if (!std::getline(file, line)) break;
                    ephData.toe = std::stod(line.substr(3, 19));
                    ephData.cic = std::stod(line.substr(22, 19));
                    ephData.omega0 = std::stod(line.substr(41, 19));
                    ephData.cis = std::stod(line.substr(60, 19));
                    
                    // 读取第五行
                    if (!std::getline(file, line)) break;
                    ephData.i0 = std::stod(line.substr(3, 19));
                    ephData.crc = std::stod(line.substr(22, 19));
                    ephData.omega = std::stod(line.substr(41, 19));
                    ephData.omegaDot = std::stod(line.substr(60, 19));
                    
                    // 读取第六行
                    if (!std::getline(file, line)) break;
                    ephData.idot = std::stod(line.substr(3, 19));
                    ephData.codesOnL2 = std::stod(line.substr(22, 19));
                    ephData.gpsWeek = std::stod(line.substr(41, 19));
                    ephData.l2pFlag = std::stod(line.substr(60, 19));
                    
                    // 读取第七行
                    if (!std::getline(file, line)) break;
                    ephData.svAccuracy = std::stod(line.substr(3, 19));
                    ephData.svHealth = std::stod(line.substr(22, 19));
                    ephData.tgd = std::stod(line.substr(41, 19));
                    ephData.iodc = std::stod(line.substr(60, 19));
                    
                    // 读取第八行
                    if (!std::getline(file, line)) break;
                    ephData.transmissionTime = std::stod(line.substr(3, 19));
                    ephData.fitInterval = std::stod(line.substr(22, 19));
                    
                    // 创建卫星轨道对象并设置星历数据
                    GPSSatelliteOrbit orbit;
                    orbit.setPRN(satId);
                    
                    // 将EphemerisData转换为轨道参数向量
                    std::vector<double> orbitParams;
                    orbitParams.push_back(ephData.toe);       // 0: 星历参考时间
                    orbitParams.push_back(ephData.sqrtA);     // 1: 轨道长半轴平方根
                    orbitParams.push_back(ephData.e);         // 2: 偏心率
                    orbitParams.push_back(ephData.i0);        // 3: 轨道倾角
                    orbitParams.push_back(ephData.omega0);    // 4: 升交点赤经
                    orbitParams.push_back(ephData.omega);     // 5: 近地点角距
                    orbitParams.push_back(ephData.m0);        // 6: 平近点角
                    orbitParams.push_back(ephData.deltaN);    // 7: 平均角速度改正项
                    orbitParams.push_back(ephData.idot);      // 8: 轨道倾角变化率
                    orbitParams.push_back(ephData.omegaDot);  // 9: 升交点赤经变化率
                    orbitParams.push_back(ephData.cuc);       // 10: 纬度幅角余弦调和改正项
                    orbitParams.push_back(ephData.cus);       // 11: 纬度幅角正弦调和改正项
                    orbitParams.push_back(ephData.crc);       // 12: 径向余弦调和改正项
                    orbitParams.push_back(ephData.crs);       // 13: 径向正弦调和改正项
                    orbitParams.push_back(ephData.cic);       // 14: 轨道倾角余弦调和改正项
                    orbitParams.push_back(ephData.cis);       // 15: 轨道倾角正弦调和改正项
                    orbitParams.push_back(ephData.af0);       // 16: 钟差多项式常数项
                    orbitParams.push_back(ephData.af1);       // 17: 钟差多项式一次项
                    orbitParams.push_back(ephData.af2);       // 18: 钟差多项式二次项
                    
                    orbit.setOrbitParams(orbitParams);
                    
                    // 存储到卫星轨道映射中
                    satelliteOrbits_[satId] = orbit;
                    
                } catch (const std::exception& e) {
                    std::cerr << "解析导航记录时出错: " << e.what() << std::endl;
                }
            }
        }
    } else if (version_ == RinexVersion::V3x) {
        // RINEX 3.x导航消息格式
        std::string currentSystem;
        
        while (std::getline(file, line)) {
            // 检查是否是卫星行
            if (line.length() >= 3 && line[0] != ' ') {
                std::string satId = line.substr(0, 3);
                currentSystem = satId.substr(0, 1);
                
                // 检查是否是我们要处理的系统
                if (enabledSystems_.empty() || 
                    std::find(enabledSystems_.begin(), enabledSystems_.end(), currentSystem) != enabledSystems_.end()) {
                    
                    // 解析历元时间
                    try {
                        int year = std::stoi(line.substr(4, 4));
                        int month = std::stoi(line.substr(9, 2));
                        int day = std::stoi(line.substr(12, 2));
                        int hour = std::stoi(line.substr(15, 2));
                        int minute = std::stoi(line.substr(18, 2));
                        double second = std::stod(line.substr(21, 2));
                        
                        // 创建星历数据结构
                        EphemerisData ephData;
                        ephData.prn = satId;
                        ephData.year = year;
                        ephData.month = month;
                        ephData.day = day;
                        ephData.hour = hour;
                        ephData.minute = minute;
                        ephData.second = second;
                        
                        // 解析卫星钟差参数
                        ephData.af0 = std::stod(line.substr(23, 19));
                        ephData.af1 = std::stod(line.substr(42, 19));
                        ephData.af2 = std::stod(line.substr(61, 19));
                        
                        // 根据不同的导航系统，读取不同数量的行
                        int numLines = 7; // GPS默认为7行
                        
                        if (currentSystem == "G") { // GPS
                            numLines = 7;
                        } else if (currentSystem == "R") { // GLONASS
                            numLines = 3;
                        } else if (currentSystem == "E") { // Galileo
                            numLines = 7;
                        } else if (currentSystem == "C") { // BeiDou
                            numLines = 7;
                        } else if (currentSystem == "J") { // QZSS
                            numLines = 7;
                        }
                        
                        // 读取剩余的行
                        std::vector<std::string> navLines;
                        for (int i = 0; i < numLines; ++i) {
                            if (!std::getline(file, line)) break;
                            navLines.push_back(line);
                        }
                        
                        // 根据不同的导航系统，解析不同的参数
                        if (currentSystem == "G" || currentSystem == "E" || currentSystem == "C" || currentSystem == "J") {
                            // GPS/Galileo/BeiDou/QZSS格式类似
                            if (navLines.size() >= 7) {
                                // 第一行
                                ephData.iode = std::stod(navLines[0].substr(4, 19));
                                ephData.crs = std::stod(navLines[0].substr(23, 19));
                                ephData.deltaN = std::stod(navLines[0].substr(42, 19));
                                ephData.m0 = std::stod(navLines[0].substr(61, 19));
                                
                                // 第二行
                                ephData.cuc = std::stod(navLines[1].substr(4, 19));
                                ephData.e = std::stod(navLines[1].substr(23, 19));
                                ephData.cus = std::stod(navLines[1].substr(42, 19));
                                ephData.sqrtA = std::stod(navLines[1].substr(61, 19));
                                
                                // 第三行
                                ephData.toe = std::stod(navLines[2].substr(4, 19));
                                ephData.cic = std::stod(navLines[2].substr(23, 19));
                                ephData.omega0 = std::stod(navLines[2].substr(42, 19));
                                ephData.cis = std::stod(navLines[2].substr(61, 19));
                                
                                // 第四行
                                ephData.i0 = std::stod(navLines[3].substr(4, 19));
                                ephData.crc = std::stod(navLines[3].substr(23, 19));
                                ephData.omega = std::stod(navLines[3].substr(42, 19));
                                ephData.omegaDot = std::stod(navLines[3].substr(61, 19));
                                
                                // 第五行
                                ephData.idot = std::stod(navLines[4].substr(4, 19));
                                
                                // 第六行
                                ephData.svAccuracy = std::stod(navLines[5].substr(4, 19));
                                ephData.svHealth = std::stod(navLines[5].substr(23, 19));
                                ephData.tgd = std::stod(navLines[5].substr(42, 19));
                                
                                // 创建卫星轨道对象并设置星历数据
                                GPSSatelliteOrbit orbit;
                                orbit.setPRN(satId);
                                
                                // 将EphemerisData转换为轨道参数向量
                                std::vector<double> orbitParams;
                                orbitParams.push_back(ephData.toe);       // 0: 星历参考时间
                                orbitParams.push_back(ephData.sqrtA);     // 1: 轨道长半轴平方根
                                orbitParams.push_back(ephData.e);         // 2: 偏心率
                                orbitParams.push_back(ephData.i0);        // 3: 轨道倾角
                                orbitParams.push_back(ephData.omega0);    // 4: 升交点赤经
                                orbitParams.push_back(ephData.omega);     // 5: 近地点角距
                                orbitParams.push_back(ephData.m0);        // 6: 平近点角
                                orbitParams.push_back(ephData.deltaN);    // 7: 平均角速度改正项
                                orbitParams.push_back(ephData.idot);      // 8: 轨道倾角变化率
                                orbitParams.push_back(ephData.omegaDot);  // 9: 升交点赤经变化率
                                orbitParams.push_back(ephData.cuc);       // 10: 纬度幅角余弦调和改正项
                                orbitParams.push_back(ephData.cus);       // 11: 纬度幅角正弦调和改正项
                                orbitParams.push_back(ephData.crc);       // 12: 径向余弦调和改正项
                                orbitParams.push_back(ephData.crs);       // 13: 径向正弦调和改正项
                                orbitParams.push_back(ephData.cic);       // 14: 轨道倾角余弦调和改正项
                                orbitParams.push_back(ephData.cis);       // 15: 轨道倾角正弦调和改正项
                                orbitParams.push_back(ephData.af0);       // 16: 钟差多项式常数项
                                orbitParams.push_back(ephData.af1);       // 17: 钟差多项式一次项
                                orbitParams.push_back(ephData.af2);       // 18: 钟差多项式二次项
                                
                                orbit.setOrbitParams(orbitParams);
                                
                                // 存储到卫星轨道映射中
                                satelliteOrbits_[satId] = orbit;
                            }
                        } else if (currentSystem == "R") {
                            // GLONASS格式不同，需要特殊处理
                            // 这里简化处理，实际应根据GLONASS星历格式进行解析
                        }
                        
                    } catch (const std::exception& e) {
                        std::cerr << "解析导航记录时出错: " << e.what() << std::endl;
                    }
                } else {
                    // 跳过不需要处理的系统的行
                    for (int i = 0; i < 7; ++i) {
                        if (!std::getline(file, line)) break;
                    }
                }
            }
        }
    }
    
    // 初始化卫星轨道
    initializeSatelliteOrbits();
}

// 实现setMinElevation方法
void RinexParser::setMinElevation(double minElevation) {
    minElevation_ = minElevation;
}

// 在合适的位置添加GNSSObservation结构的扩展方法，可以获取测站位置
std::vector<double> RinexParser::getStationPosition(const GNSSObservation& obs) {
    // 如果观测值中有测站位置，直接返回
    if (obs.stationPosition.size() == 3) {
        return obs.stationPosition;
    }
    
    // 没有测站位置时，尝试从stationInfo_中获取
    if (obs.station >= 0) {
        std::string stationName = obs.getStation();
        if (stationName == stationInfo_.name || stationName == stationInfo_.id) {
            return {stationInfo_.x, stationInfo_.y, stationInfo_.z};
        }
    }
    
    // 返回零向量表示无效坐标
    return {0.0, 0.0, 0.0};
} 